package demoxsgl_300.com.gouwu1500.certificateCamera;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.tencent.cos.xml.CosXmlService;
import com.tencent.cos.xml.CosXmlServiceConfig;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.listener.CosXmlProgressListener;
import com.tencent.cos.xml.model.CosXmlResult;
import com.tencent.cos.xml.transfer.UploadService;
import com.tencent.qcloud.core.auth.QCloudCredentialProvider;
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import demoxsgl_300.com.gouwu1500.R;
import demoxsgl_300.com.gouwu1500.http.API;
import demoxsgl_300.com.gouwu1500.http.Okhttp;
import demoxsgl_300.com.gouwu1500.zhi.Content;
import demoxsgl_300.com.gouwu1500.zhi.FaZuoTeDian_1_Activity;
import demoxsgl_300.com.gouwu1500.zhi.XuanZeActivity;

/**
 * Created by smartown on 2018/2/24 11:46.
 * <br>
 * Desc:
 * <br>
 * 拍照界面
 */
public class CameraActivity extends Activity implements View.OnClickListener {
    private String appid = "1256678596";  //上传图片的appid
    private String region = "ap-beijing";//上传图片的区域名
    com.tencent.cos.xml.CosXmlServiceConfig CosXmlServiceConfigs = new CosXmlServiceConfig.Builder()
            .setAppidAndRegion(appid, region)
            .setDebuggable(true)
            .builder();
    /**
     * 拍摄类型-身份证正面
     */
    public final static int TYPE_IDCARD_FRONT = 1;
    /**
     * 拍摄类型-身份证反面
     */
    public final static int TYPE_IDCARD_BACK = 2;
    /**
     * 拍摄类型-竖版营业执照
     */
    public final static int TYPE_COMPANY_PORTRAIT = 3;
    /**
     * 拍摄类型-横版营业执照
     */
    public final static int TYPE_COMPANY_LANDSCAPE = 4;

    public final static int REQUEST_CODE = 0X13;
    public final static int RESULT_CODE = 0X14;

    /**
     * @param type {@link #TYPE_IDCARD_FRONT}
     *             {@link #TYPE_IDCARD_BACK}
     *             {@link #TYPE_COMPANY_PORTRAIT}
     *             {@link #TYPE_COMPANY_LANDSCAPE}
     */
    public static void openCertificateCamera(Activity activity, int type, String v) {
        Intent intent = new Intent(activity, CameraActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("nian", v);
        activity.startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * @return 结果文件路径
     */
    public static String getResult(Intent data) {
        if (data != null) {
            return data.getStringExtra("result");
        }
        return "";
    }

    private CameraPreview cameraPreview;
    private View containerView;
    private ImageView cropView;
    private ImageView flashImageView;
    private View optionView;
    private View resultView;

    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initMediaPlayer();
        type = getIntent().getIntExtra("type", 0);
        String nian = getIntent().getStringExtra("nian");
        if (type == TYPE_COMPANY_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        setContentView(R.layout.activity_camera);
        cameraPreview = (CameraPreview) findViewById(R.id.camera_surface);
        TextView fanhui = (TextView) findViewById(R.id.fanhui);
        fanhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //获取屏幕最小边，设置为cameraPreview较窄的一边
        float screenMinSize = Math.min(getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
        //根据screenMinSize，计算出cameraPreview的较宽的一边，长宽比为标准的16:9
        float maxSize = screenMinSize / 9.0f * 16.0f;
        RelativeLayout.LayoutParams layoutParams;
        if (type == TYPE_COMPANY_PORTRAIT) {
            layoutParams = new RelativeLayout.LayoutParams((int) screenMinSize, (int) maxSize);
        } else {
            layoutParams = new RelativeLayout.LayoutParams((int) maxSize, (int) screenMinSize);
        }
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        cameraPreview.setLayoutParams(layoutParams);

        containerView = findViewById(R.id.camera_crop_container);
        cropView = (ImageView) findViewById(R.id.camera_crop);
        if (type == TYPE_COMPANY_PORTRAIT) {
            float width = (int) (screenMinSize * 0.8);
            float height = (int) (width * 43.0f / 30.0f);
            LinearLayout.LayoutParams containerParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) height);
            LinearLayout.LayoutParams cropParams = new LinearLayout.LayoutParams((int) width, (int) height);
            containerView.setLayoutParams(containerParams);
            cropView.setLayoutParams(cropParams);
        } else if (type == TYPE_COMPANY_LANDSCAPE) {
            float height = (int) (screenMinSize * 0.8);
            float width = (int) (height * 43.0f / 30.0f);
            LinearLayout.LayoutParams containerParams = new LinearLayout.LayoutParams((int) width, ViewGroup.LayoutParams.MATCH_PARENT);
            LinearLayout.LayoutParams cropParams = new LinearLayout.LayoutParams((int) width, (int) height);
            containerView.setLayoutParams(containerParams);
            cropView.setLayoutParams(cropParams);
        } else {
            float height = (int) (screenMinSize * 0.75);
            float width = (int) (height * 75.0f / 47.0f);
            LinearLayout.LayoutParams containerParams = new LinearLayout.LayoutParams((int) width, ViewGroup.LayoutParams.MATCH_PARENT);
            LinearLayout.LayoutParams cropParams = new LinearLayout.LayoutParams((int) width, (int) height);
            containerView.setLayoutParams(containerParams);
            cropView.setLayoutParams(cropParams);
        }
        switch (type) {
            case TYPE_IDCARD_FRONT:
//                cropView.setImageResource(R.mipmap.back2);
                break;
            case TYPE_IDCARD_BACK:
//                cropView.setImageResource(R.mipmap.back2);
                break;
            case TYPE_COMPANY_PORTRAIT:
//                cropView.setImageResource(R.mipmap.camera_company);
                break;
            case TYPE_COMPANY_LANDSCAPE:
//                cropView.setImageResource(R.mipmap.camera_company_landscape);
                break;
        }

        flashImageView = (ImageView) findViewById(R.id.camera_flash);
        optionView = findViewById(R.id.camera_option);
        resultView = findViewById(R.id.camera_result);
        cameraPreview.setOnClickListener(this);
        findViewById(R.id.camera_close).setOnClickListener(this);
        findViewById(R.id.camera_take).setOnClickListener(this);
        flashImageView.setOnClickListener(this);
        findViewById(R.id.camera_result_ok).setOnClickListener(this);
        findViewById(R.id.camera_result_cancel).setOnClickListener(this);
        if (nian.equals("1")) {
            //播放语音
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
            }
        }

//        break;
//        case R.id.btnPause:
//        //如果在播放中，立刻暂停。
//        if (mediaPlayer.isPlaying()) {
//            mediaPlayer.pause();
//        }
//        break;
//        case R.id.btnStop:
//        //如果在播放中，立刻停止。
//        if (mediaPlayer.isPlaying()) {
//            mediaPlayer.reset();
//            initMediaPlayer();//初始化播放器 MediaPlayer
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.camera_surface) {
            cameraPreview.focus();
        } else if (id == R.id.camera_close) {
            finish();
        } else if (id == R.id.camera_take) {
            takePhoto();
        } else if (id == R.id.camera_flash) {
            boolean isFlashOn = cameraPreview.switchFlashLight();
            flashImageView.setImageResource(isFlashOn ? R.mipmap.camera_flash_on : R.mipmap.camera_flash_off);
        } else if (id == R.id.camera_result_ok) {
            goBack();
        } else if (id == R.id.camera_result_cancel) {
            optionView.setVisibility(View.VISIBLE);
            cameraPreview.setEnabled(true);
            resultView.setVisibility(View.GONE);
            cameraPreview.startPreview();
        }
    }

    String path;

    private void takePhoto() {

        optionView.setVisibility(View.GONE);
        cameraPreview.setEnabled(false);
        cameraPreview.takePhoto(new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(final byte[] data, Camera camera) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        File originalFile = getOriginalFile();
                        FileOutputStream originalFileOutputStream = null;
                        try {
                            originalFileOutputStream = new FileOutputStream(originalFile);
                            originalFileOutputStream.write(data);
                            originalFileOutputStream.close();
                            path = originalFile.getPath();
                            Log.e("zzz", "xx" + path);
//
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                uploadPhoto(path);
                            }
                        });
                    }
                }).start();


            }
        });

    }

    /**
     * @return 拍摄图片原始文件
     */
    private File getOriginalFile() {
        switch (type) {
            case TYPE_IDCARD_FRONT:
                return new File(getSDPath(), "idCardFront.jpg");

        }
        return new File(getSDPath(), "picture.jpg");
    }

    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    /**
     * @return 拍摄图片裁剪文件
     */
    private File getCropFile() {
        switch (type) {
            case TYPE_IDCARD_FRONT:
                return new File(getExternalCacheDir(), "idCardFrontCrop.jpg");
            case TYPE_IDCARD_BACK:
                return new File(getExternalCacheDir(), "idCardBackCrop.jpg");
            case TYPE_COMPANY_PORTRAIT:
            case TYPE_COMPANY_LANDSCAPE:
                return new File(getExternalCacheDir(), "companyInfoCrop.jpg");
        }
        return new File(getExternalCacheDir(), "pictureCrop.jpg");
    }

    /**
     * 点击对勾，使用拍照结果，返回对应图片路径
     */
    private void goBack() {
        Intent intent = new Intent();
        intent.putExtra("result", getCropFile().getPath());
        setResult(RESULT_CODE, intent);
        finish();
    }


    //上传到腾讯云cos
    public void uploadPhoto(String mFilePath) {
        showdialog();
        Log.e("上传到cos文件路径", mFilePath);
        String fileName = mFilePath.substring(29);
        QCloudCredentialProvider QCloudCredentialProvider = new ShortTimeCredentialProvider("AKIDERadYMzb5OXXQ9EIguW5ZyJZjnldt5gC", "fFesvnkXAe0IPL5d1EG6lHcv57zgDZkk", 300);
        Log.e("&&&&&", QCloudCredentialProvider.toString());
        CosXmlService CosXmlService = new CosXmlService(this, CosXmlServiceConfigs, QCloudCredentialProvider);
        UploadService.ResumeData uploadData = new UploadService.ResumeData();
        uploadData.bucket = "huihu-1256678596";
        uploadData.cosPath = fileName; //格式如 cosPath = "test.txt";
        uploadData.srcPath = mFilePath; // 如 srcPath =Environment.getExternalStorageDirectory().getPath() + "/test.txt";
        uploadData.sliceSize = 1024 * 1024; //每个分片的大小
        uploadData.uploadId = null; // 若是续传，则uploadId不为空
        UploadService uploadService = new UploadService(CosXmlService, uploadData);
        uploadService.setProgressListener(new CosXmlProgressListener() {
            @Override
            public void onProgress(long progress, long max) {
                // todo Do something to update progress...
                Log.e("++++", "" + progress);
            }
        });
        /**
         * 开始上传
         */
        try {
            CosXmlResult cosXmlResult = uploadService.upload();
            Log.e("++++", cosXmlResult.toString());
            Log.e("++++", cosXmlResult.printResult());
            Log.e("++++", cosXmlResult.accessUrl);
            postFile("http://" + cosXmlResult.accessUrl);
        } catch (CosXmlClientException e) {
            // mProgressDialog.dismiss();
            e.printStackTrace();
            try {
                if (dialog != null) {
                    dialog.dismiss();
                }
                Toast.makeText(CameraActivity.this, "上传失败，请检查您的网络连接！", Toast.LENGTH_SHORT).show();
                takePhoto(1);
                return;
            } catch (Exception e1) {
                Looper.prepare();
                if (dialog != null) {
                    dialog.dismiss();
                }
                Toast.makeText(CameraActivity.this, "上传失败，请检查您的网络连接！", Toast.LENGTH_SHORT).show();

                Looper.loop();
                takePhoto(1);
                return;
            }
        } catch (CosXmlServiceException e2) {
            //mProgressDialog.dismiss();
            e2.printStackTrace();
            try {
                if (dialog != null) {
                    dialog.dismiss();
                }
                Toast.makeText(CameraActivity.this, "上传失败！", Toast.LENGTH_SHORT).show();
                takePhoto(1);
                return;
            } catch (Exception e1) {
                Looper.prepare();
                if (dialog != null) {
                    dialog.dismiss();
                }
                Toast.makeText(CameraActivity.this, "上传失败！", Toast.LENGTH_SHORT).show();

                Looper.loop();
                takePhoto(1);
                return;
            }
        } catch (Exception e3) {
            e3.printStackTrace();
            try {
                if (dialog != null) {
                    dialog.dismiss();
                }
                takePhoto(1);
                Toast.makeText(CameraActivity.this, "服务正在升级...，请稍后再试！", Toast.LENGTH_SHORT).show();
                return;
            } catch (Exception e1) {
                Looper.prepare();
                if (dialog != null) {
                    dialog.dismiss();
                }

                Toast.makeText(CameraActivity.this, "服务正在升级...，请稍后再试！", Toast.LENGTH_SHORT).show();
                Looper.loop();
                takePhoto(1);
                return;
            }
        }
    }

    public void showdialog() {
        dialog = KProgressHUD.create(CameraActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f).setCancellable(false)
                .show();
    }

    KProgressHUD dialog;

    public void postFile(String path) {
        API.tongue(path, new Okhttp.Objectcallback() {
            @Override
            public void onsuccess(String st) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                Log.e("111", "xx" + st);
                cameraPreview.setEnabled(true);
                cameraPreview.release();
                if (st.equals("unsuccess")) {
                    Toast.makeText(CameraActivity.this, "照片质量过低，无法识别！", Toast.LENGTH_SHORT).show();
                    takePhoto(1);


                } else {
                    Content.SheTou = st;
                    startActivity(new Intent(CameraActivity.this, XuanZeActivity.class));
                    finish();
                }
//

            }

            @Override
            public void onFalia(int code, String errst) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                Log.e("111", "xx" + errst);
                Toast.makeText(CameraActivity.this, "网络错误" + errst, Toast.LENGTH_SHORT).show();
                takePhoto(1);

            }
        });
    }

    private void takePhoto(int type) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 0x12);
            return;
        }
        CameraActivity.openCertificateCamera(this, type, "2");
        finish();
    }


    MediaPlayer mediaPlayer = new MediaPlayer();

    private void initMediaPlayer() {
        try {
       //初始化语音
            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.m);
            mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());//指定音频文件路径
            mediaPlayer.setLooping(false);//设置为循环播放
            mediaPlayer.prepare();//初始化播放器MediaPlayer

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
};









